package com.je.paas.document.controller;

import cn.hutool.core.io.IoUtil;
import com.je.core.base.JERequestWrapper;
import com.je.core.exception.PlatformException;
import com.je.core.exception.PlatformExceptionEnum;
import com.je.core.util.SecurityUserHolder;
import com.je.paas.document.model.bo.FileBO;
import com.je.paas.document.service.DocumentBusService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * DocumentControllerOld
 *
 * @author wangmm@ketr.com.cn
 * @date 2019/10/18
 */
@Controller("documentControllerOld")
@RequestMapping(value = "/je/doc/document")
public class DocumentControllerOld {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private DocumentBusService documentBusService;

    /**
     * 文件下载 兼容老接口
     *
     * @param response 响应
     * @param path     文件唯一标识
     * @return void
     */
    @RequestMapping(value = {"/download","/doLoadFile"})
    @ResponseBody
    public void download(HttpServletResponse response, String path) {
        try {
            //用户ID
            String userId = SecurityUserHolder.getCurrentUser().getUserId();
            //参数验证
            String fileKey = path;
            if (StringUtils.isEmpty(fileKey)) {
                throw new PlatformException("参数错误", PlatformExceptionEnum.UNKOWN_ERROR, request);
            }
            response.reset();
            //请求路径
            String uri = request.getRequestURI();
            //获取文件信息
            FileBO fileBO = documentBusService.downloadFile(fileKey, userId);
            String fileName = URLEncoder.encode(fileBO.getRelName(), "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            //写入文件流
//            response.setHeader("Content-Length", fileBO.getSize().toString());
            response.setContentType(fileBO.getContentType());
            OutputStream toClient = response.getOutputStream();
            IoUtil.copy(fileBO.getFile(), toClient);
            IoUtil.close(fileBO.getFile());
            toClient.flush();
            toClient.close();
        } catch (PlatformException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new PlatformException("文件查找错误", PlatformExceptionEnum.UNKOWN_ERROR, request, e);
        }
    }


}